﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace XXF.BaseService.ServiceCenter.Service.Visitor
{
   /// <summary>
   /// 服务访问拦截
   /// </summary>
    public class ServerVisitProvider
    {
        private int errorcount;
        private int connectioncount;
        private int visitcount;

        public int ErrorCount { get { return errorcount; } }
        public int ConnectionCount { get { return connectioncount; } }
        public int VisitCount { get { return visitcount; } }
      
        public T Visit<T>(Func<T> action)
        {
            T r = default(T);
            try
            {
                Interlocked.Increment(ref connectioncount);
                Interlocked.Increment(ref visitcount);
                r = action.Invoke();
            }
            catch (Exception exp)
            {
                Interlocked.Increment(ref errorcount);
            }
            finally
            {
                Interlocked.Decrement(ref connectioncount);  
            }
            return r;
            
        }

        public void Visit(Action action)
        {
            try
            {
                Interlocked.Increment(ref connectioncount);
                Interlocked.Increment(ref visitcount);
                action.Invoke();
            }
            catch (Exception exp)
            {
                Interlocked.Increment(ref errorcount);
            }
            finally
            {
                Interlocked.Decrement(ref connectioncount);
            }
        }
    }
}
